<template>
  <a-drawer :visible="visible" title="渠道公司" :width="1300" @close="closeDrawer">
    <a-table :columns="columns" :data-source="tableData" :pagination="pagination" :loading="loading"
             @change="handleTableChange" :scroll="{ x: 'max-content' }">
      <template #title>
        <div class="flex justify-between ">

          <div class="flex-1">
            <a-form layout="vertical" ref="formRef" :model="modelRef">
              <a-row :gutter="9" :wrap="true">
                <a-col span="4">
                  <a-form-item name="head_name">
                    <a-input placeHolder="搜索公司名称" v-model:value="modelRef.head_name"/>
                  </a-form-item>
                </a-col>
                <a-col span="4">
                  <a-form-item name="head_phone">
                    <a-input placeHolder="搜索负责人" v-model:value="modelRef.head_phone"/>
                  </a-form-item>
                </a-col>
                <a-col span="4">
                  <a-form-item name="name">
                    <a-input placeHolder="搜索负责人号码" v-model:value="modelRef.name"/>
                  </a-form-item>
                </a-col>
                <a-col span="4">
                  <a-form-item name="tax_id">
                    <a-input placeHolder="搜索税号" v-model:value="modelRef.tax_id"/>
                  </a-form-item>
                </a-col>
                <a-col span="4">
                  <a-form-item>
                    <a-select placeholder="审核状态" :options="approvalOptions"
                              v-model:value="modelRef.approval_status"></a-select>
                  </a-form-item>
                </a-col>
                <a-col span="4">
                  <a-form-item>
                    <a-select placeholder="是否签订合作协议" :options="signOptions"
                              v-model:value="modelRef.is_sign"></a-select>
                  </a-form-item>
                </a-col>
                <a-col span="6">
                  <a-form-item>
                    <a-range-picker v-model:value="sign_range" :valueFormat="dateFormatStr"
                                    @change="signDateChange"
                                    :placeholder="['签订开始日期', '签订结束日期']"/>
                  </a-form-item>
                </a-col>
                <a-col span="6">
                  <a-form-item>
                    <a-range-picker v-model:value="end_range" :valueFormat="dateFormatStr"
                                    @change="endDateChange"
                                    :placeholder="['到期开始日期', '到期结束日期']"/>
                  </a-form-item>
                </a-col>

                <a-col>
                  <a-space>
                    <a-button type="primary" @click="toSearch">搜索</a-button>
                    <a-button @click="reset">重置</a-button>
                  </a-space>
                </a-col>
                <a-col style="margin-left: auto">
                  <a-button type="primary" @click="addCompany">+新增公司</a-button>
                </a-col>
              </a-row>
            </a-form>

          </div>

        </div>

      </template>
      <template #bodyCell="{column,record}">
        <template v-if="column.key=='address'">
          <span>{{ record?.address?.provinceName }}</span>
          <span>{{ record?.address?.cityName }}</span>
          <span>{{ record?.address?.districtName }}</span>
          <span>{{ record?.address?.streetName }}</span>
        </template>
        <template v-if="column.key=='isSign'">
          <a-tag v-if="record.is_sign==1" color="blue">已签署</a-tag>
          <a-tag v-if="record.is_sign==0">未签署</a-tag>
        </template>

        <template v-if="column.key=='approval_status'">
          <a-tag v-if="record.approval_status==1" color="blue">已审批</a-tag>
          <a-tag v-if="record.approval_status==0">待审批</a-tag>
          <a-tag v-if="record.approval_status==2" color="red">已拒绝</a-tag>
          <a-tag v-if="record.approval_status==3">已撤销</a-tag>
        </template>
        <template v-if="column.key=='action'">
          <a-space>
            <a-button type="link" @click="editCompany(record.id)">编辑</a-button>
            <a-popconfirm
                title="确定删除该渠道公司?"
                ok-text="确认"
                cancel-text="取消"
                @confirm="deleteCompany(record.id)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>

          </a-space>
        </template>
      </template>
    </a-table>
  </a-drawer>

  <ChannelCompanyEdit :visible="editVisible" :id="editId" @toClose="editVisible = false"
                      @onCommit="editSuccess"/>

</template>

<script>
import {ref, watch, computed, reactive, toRefs} from "vue";
import ChannelCompanyEdit from "./ChannelCompanyEdit.vue";
import request from "@/common/utils/request";
import {message} from "ant-design-vue";
import {defineEmits} from "@vue/runtime-core";


export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  components: {
    ChannelCompanyEdit
  },
  emits: ["toClose"],
  setup(props, context) {

    const state = reactive({
      loading: false,
      sign_range: undefined,
      end_range: undefined,
      dateFormatStr: "YYYY-MM-DD",
      editVisible: false,
      editId: 0
    })

    const formRef = ref()
    const modelRef = reactive({
      name: "",
      tax_id: "",
      head_name: "",
      head_phone: "",
      approval_status: 1,
      is_sign: undefined,
      sign_date_start: "",
      sign_date_end: "",
      expire_date_start: "",
      expire_date_end: ""
    })

    const tableData = ref([])
    const page = ref(1)
    const limit = ref(10)
    const total = ref(0)
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true
    }))

    const getTableList = () => {
      state.loading = true
      const params = {
        page: page.value,
        pageSize: limit.value
      }
      console.log(modelRef)
      for (const key in modelRef) {
        if (key == 'is_sign' || key == 'approval_status') {
          if (modelRef[key] != undefined) {
            params[key] = modelRef[key]
          }
        } else {
          if (modelRef[key]) {
            params[key] = modelRef[key]
          }
        }
      }
      request.get("/org", "/business/customer/channel/channelCompanyList", params).then(res => {
        console.log(res)
        tableData.value = res.list
        total.value = res.total
      }).finally(() => {
        state.loading = false
      });
    }

    const handleTableChange = (pager) => {
      page.value = pager.current
      limit.value = pager.pageSize
      getTableList()
    }

    const signOptions = ref([])
    const getSignOptions = () => {
      signOptions.value = [{
        label: "是", value: 1
      }, {
        label: "否", value: 0
      }]
    }
    const approvalOptions = ref([])
    const getapprovalOptions = () => {
      approvalOptions.value = [{
        label: "待审核", value: 0
      }, {
        label: "已审核", value: 1
      }, {
        label: "拒绝", value: 2
      }, {
        label: "撤销", value: 3
      }]
    }

    const init = () => {
      getSignOptions()
      getapprovalOptions()
      getTableList()
    }


    const reset = () => {
      console.log(formRef.value)
      formRef.value.resetFields()
      modelRef.is_sign = undefined
      modelRef.sign_date_start = ""
      modelRef.sign_date_end = ""
      modelRef.expire_date_start = ""
      modelRef.expire_date_end = ""
      state.sign_range = undefined
      state.end_range = undefined
      getTableList()
    }

    const toSearch = () => {
      getTableList()
    }

    const signDateChange = (dateString) => {
      console.log(dateString)
      if (dateString.length) {
        modelRef.sign_date_start = dateString[0]
        modelRef.sign_date_end = dateString[1]
      }
      getTableList()
    }
    const endDateChange = (dateString) => {
      console.log(dateString)
      if (dateString.length) {
        modelRef.expire_date_start = dateString[0]
        modelRef.expire_date_end = dateString[1]
      }
      getTableList()
    }

    const addCompany = () => {
      state.editId = 0
      state.editVisible = true
    }

    const editCompany = (val) => {
      console.log(val)
      state.editId = val
      state.editVisible = true
    }

    const deleteCompany = (val) => {
      console.log(val)
      request.del("/org", "/business/customer/channel/channelCompanyDel", {id: val}).then(res => {
        message.success("删除成功")
        getTableList()
      })
    }

    const editSuccess = () => {
      state.editVisible = false
      getTableList()
    }

    const closeDrawer = () => {
      context.emit("toClose")
    }

    watch(() => props.visible,
        (value) => {
          if (value == true) {
            init()
          } else {
            console.log(111)
          }
        })


    const columns = [
      {
        title: "公司名称",
        key: "name",
        dataIndex: "name",
        width: 200,
        fixed: 'left'
      }, {
        title: "负责人",
        key: "head_name",
        dataIndex: "head_name"
      }, {
        title: "负责人号码",
        key: "head_phone",
        dataIndex: "head_phone"
      }, {
        title: "税号",
        key: "tax_id",
        dataIndex: "tax_id"
      }, {
        title: "所在地",
        key: "address",
        dataIndex: "address",
        width: 200
      }, {
        title: "开户行",
        key: "opening_bank",
        dataIndex: "opening_bank"
      }, {
        title: "收款账号",
        key: "receiving_account",
        dataIndex: "receiving_account"
      }, {
        title: "是否签订合作协议",
        key: "isSign",
        width: 180
      }, {
        title: "协议签订日",
        key: "sign_date",
        dataIndex: "sign_date",
        width: 150
      }, {
        title: "协议到期日",
        key: "expire_date",
        dataIndex: "expire_date",
        width: 150
      }, {
        title: "审核状态",
        key: "approval_status",
        dataIndex: "approval_status",
        width: 180
      }, {
        title: "创建时间",
        key: "created_at",
        dataIndex: "created_at",
        width: 180
      }, {
        title: "操作",
        key: "action",
        dataIndex: "",
        fixed: 'right'
      }

    ]

    return {
      ...toRefs(state),
      columns,
      addCompany,
      tableData,
      pagination,
      handleTableChange,
      reset,
      toSearch,
      formRef,
      modelRef,
      signOptions,
      signDateChange,
      endDateChange,
      deleteCompany,
      editCompany,
      editSuccess,
      closeDrawer,
      approvalOptions,

    }
  }
}
</script>

<style lang="less" scoped>
:deep(.ant-tabs-content) {
  height: 100%;
}

.ant-tag {
  margin: 4px 8px 4px 0;
}

:deep(.ant-table-title) {
  padding: 0;
}
</style>